<?php
namespace app\service;
use think\facade\Db;
use app\model\BranchModel;
use Exception;

class BranchService{ 

    public function all($params){
        $where=[];      
        if(!empty($params['keyword'])){
            $where[] = ['title','like',"%{$params['keyword']}%"];   
        }
        $users = BranchModel::where($where)->select();        
        return $users;
    } 

    public function list($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];
        if(!empty($params['keyword'])){
            $where[] = ['title','like',"%{$params['keyword']}%"];   
        }
        $data = BranchModel::where($where)->page($page,$pageCount)->order('id','desc')->select(); 
        $count = BranchModel::where($where)->count();      
        return ["list"=>$data,"count"=>$count];
    }  

    public function save($params){              
        if(empty($params['id'])){
            $data = BranchModel::where('title',$params['title'])->find();
            if($data){
                throw new Exception("部门名称已存在");
            }
            $data = BranchModel::create($params); 
        }else{
            $data = BranchModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = BranchModel::destroy($params['id']);         
        return $data;
    }
}